package com.ctw.mall.exception;

import com.ctw.mall.enums.ResponseEnum;
import com.ctw.mall.vo.ResponseVo;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotNull;


import java.util.Objects;

import static com.ctw.mall.enums.ResponseEnum.ERROR;

@ControllerAdvice
public class RuntimeExceptionHandler {
    //TODO 前端传入的json格式的数据全部为空时，不能得到异常错误的msg，得到的是
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody//返回json格式
  //  @ResponseStatus(HttpStatus.FORBIDDEN)
    public ResponseVo handle(@NotNull RuntimeException e){
        return ResponseVo.error(ERROR,e.getMessage());
    }

    //捕获异常
    @ExceptionHandler(UserLoginException.class)
    @ResponseBody
    public ResponseVo userLoginHandle(){
        return  ResponseVo.error(ResponseEnum.NEED_LOGIN);
    }


    //"/carts"，统一校验抛出的异常，拦截异常，并提示
    //由于在此处做了统一的拦截，用户的登录注册接口就可以简化
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseVo notValidExceptionHandle(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Objects.requireNonNull(bindingResult.getFieldError());
        return ResponseVo.error(ResponseEnum.PARAM_ERROR,
                bindingResult.getFieldError().getField()+" "+bindingResult.getFieldError().getDefaultMessage());
    }
}
